<?php

namespace Ignus\View\TokenParser;

use Ignus\View\TokenParser;
use Ignus\View\Token;
use Ignus\View\Error\Syntax;

class AutoEscape extends TokenParser
{
    public function parse(Token $token)
    {
        $lineno = $token->getLine();
        $value = $this->parser->getStream()->expect(Token::NAME_TYPE)->getValue();
        if (!in_array($value, array('true', 'false'))) {
            throw new Syntax("Autoescape value must be 'true' or 'false'", $lineno);
        }
        $value = 'true' === $value ? 'html' : false;

        if ($this->parser->getStream()->test(Token::NAME_TYPE)) {
            if (false === $value) {
                throw new Syntax('Unexpected escaping strategy as you set autoescaping to false.', $lineno);
            }

            $value = $this->parser->getStream()->next()->getValue();
        }

        $this->parser->getStream()->expect(Token::BLOCK_END_TYPE);
        $body = $this->parser->subparse(array($this, 'decideBlockEnd'), true);
        $this->parser->getStream()->expect(Token::BLOCK_END_TYPE);

        return new \Ignus\View\Node\AutoEscape($value, $body, $lineno, $this->getTag());
    }

    public function decideBlockEnd(Token $token)
    {
        return $token->test('endautoescape');
    }

    public function getTag()
    {
        return 'autoescape';
    }
}
